import React, { useState } from 'react';
import { Upload, message } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Dragger } = Upload;

/**
 * 阿里云OSS文件上传组件
 */
const OssUpload = ({ 
  onSuccess, 
  onError, 
  accept = "*", 
  maxSize = 10, // MB
  multiple = false,
  listType = "text",
  children 
}) => {
  const [uploading, setUploading] = useState(false);

  const beforeUpload = (file) => {
    // 检查文件大小
    const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
    if (!isLtMaxSize) {
      message.error(`文件大小不能超过 ${maxSize}MB!`);
      return false;
    }

    return true;
  };

  const customRequest = async ({ file, onProgress, onSuccess: uploadSuccess, onError: uploadError }) => {
    try {
      setUploading(true);
      
      // 获取OSS上传签名
      const token = localStorage.getItem('admin_token');
      const signResponse = await axios.post('/api/oss/signature', 
        {
          fileName: file.name,
          fileType: file.type
        },
        { 
          headers: { Authorization: `Bearer ${token}` }
        }
      );

      const { signature, policy, accessKeyId, host, key } = signResponse.data.data;

      // 构建FormData
      const formData = new FormData();
      formData.append('key', key);
      formData.append('policy', policy);
      formData.append('OSSAccessKeyId', accessKeyId);
      formData.append('signature', signature);
      formData.append('file', file);

      // 上传到阿里云OSS
      console.log('开始上传到OSS:', { host, key, fileName: file.name });
      const uploadResponse = await axios.post(host, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        },
        timeout: 60000, // 60秒超时
      });

      const fileUrl = `${host}/${key}`;
      
      uploadSuccess({
        name: file.name,
        url: fileUrl,
        status: 'done'
      });

      if (onSuccess) {
        onSuccess({
          name: file.name,
          url: fileUrl,
          size: file.size,
          type: file.type
        });
      }

      message.success('文件上传成功');
      
    } catch (error) {
      console.error('文件上传失败:', error);
      console.error('错误详情:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
        config: error.config
      });
      
      uploadError(error);
      
      if (onError) {
        onError(error);
      }
      
      // 根据错误类型显示不同的错误信息
      let errorMessage = '文件上传失败，请重试';
      if (error.response) {
        if (error.response.status === 403) {
          errorMessage = 'OSS权限不足，请检查配置';
        } else if (error.response.status === 400) {
          errorMessage = '上传参数错误，请重试';
        } else if (error.response.status >= 500) {
          errorMessage = 'OSS服务异常，请稍后重试';
        }
      } else if (error.code === 'ECONNABORTED') {
        errorMessage = '上传超时，请检查网络连接';
      }
      
      message.error(errorMessage);
    } finally {
      setUploading(false);
    }
  };

  const uploadProps = {
    name: 'file',
    multiple,
    accept,
    listType,
    beforeUpload,
    customRequest,
    showUploadList: {
      showPreviewIcon: true,
      showRemoveIcon: true,
    },
  };

  if (children) {
    return (
      <Upload {...uploadProps}>
        {children}
      </Upload>
    );
  }

  return (
    <Dragger {...uploadProps}>
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p className="ant-upload-hint">
        支持单个或批量上传，文件大小不超过{maxSize}MB
      </p>
    </Dragger>
  );
};

export default OssUpload;
